package com.cheli.managerAsset.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cheli.managerAsset.entity.AsCategory;
import com.cheli.managerAsset.entity.excel.CategoryData;
import com.cheli.managerAsset.entity.subject.OneCategory;
import com.cheli.managerAsset.entity.subject.TwoCategory;
import com.cheli.managerAsset.listener.CategoryExcelListener;
import com.cheli.managerAsset.mapper.AsCategoryMapper;
import com.cheli.managerAsset.service.AsCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 资产分类 服务实现类
 * </p>
 *
 * @author cheli
 * @since 2021-03-14
 */
@Service
@Slf4j
public class AsCategoryServiceImpl extends ServiceImpl<AsCategoryMapper, AsCategory> implements AsCategoryService {


    @Override
    public void saveCategory(MultipartFile multipartFile, AsCategoryService categoryService) {
        try{
            InputStream in = multipartFile.getInputStream();
            EasyExcel.read(in, CategoryData.class, new CategoryExcelListener(categoryService))
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            log.error(e.toString());
        }
    }

    @Override
    public List<OneCategory> getAllCategory() {
       QueryWrapper<AsCategory> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id", "0");
        List<AsCategory> oneCategoryList = baseMapper.selectList(wrapperOne);


       QueryWrapper<AsCategory> wrapperTwo = new QueryWrapper<>();
        wrapperOne.ne("parent_id", "0");
        List<AsCategory> twoCategoryList = baseMapper.selectList(wrapperTwo);

        List<OneCategory> finalCateList = new ArrayList<>();

       for (AsCategory category: oneCategoryList) {

            OneCategory oneCategory = new OneCategory();
            BeanUtils.copyProperties(category, oneCategory);

            List<TwoCategory> twoFinalCategoryList = new ArrayList<>();

            for (AsCategory tCategory: twoCategoryList) {

                if(category.getId().equals(tCategory.getParentId())){
                    TwoCategory twoCategory = new TwoCategory();
                    BeanUtils.copyProperties(tCategory, twoCategory);
                    twoFinalCategoryList.add(twoCategory);
                }
            }
            oneCategory.setChildren(twoFinalCategoryList);

            finalCateList.add(oneCategory);
        }
        return finalCateList;
    }
}
